// pages/detail-song/detail-song.js
import recommendStore from "../../store/recommendStore"
import rankingStore from "../../store/rankingStore"
import { getPlaylistdetail } from "../../serive/music"
import playerStore from "../../store/playerStore"

Page({
  data: {
    songInfo:{},
    type:"",
    key:"",
    id:-1
  },
  onLoad(options) {
    const type = options.type
    if (type === "ranking") {
        const key = options.key
        rankingStore.onState(key,this.handleRanking)
        this.setData({ type,key })
    } else if (type === "recommend") {
        const key = options.key
        recommendStore.onState(key,this.handleRanking)
        this.setData({ type,key })
    } else if (type === "menu") {
        const id = options.id
        this.setData({ type,id })
        this.fetchMenuSongInfo()
    }
},
  async fetchMenuSongInfo() {
    const res = await getPlaylistdetail(this.data.id)
    this.setData({ songInfo: res.playlist }) 
  },
  handleRanking(value) {
    if (!value.name) return 
    this.setData({ songInfo: value })
    wx.setNavigationBarTitle({
        title: value.name,
    })
  },
  onSongItemTap(event) {
    const index = event.currentTarget.dataset.index
    playerStore.setState("playSongList",this.data.songInfo.tracks)
    playerStore.setState("playSongIndex",index)
  },
  onUnload() {
    // 性能优化，在卸载该页面时取消监听
    if(this.data.type === "ranking") {
        rankingStore.offState(this.data.key,this.handleRanking)
    } else if (this.data.type === "recommend") {
        recommendStore.offState(this.data.key,this.handleRanking)
    }
  }
})